import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author bigbird-0101
 * @date 2024-02-21 10:28
 */
public class VirtualThreadHttpServer {
    static ThreadLocalRandom current = ThreadLocalRandom.current();
    protected static final String TIME_MAX_LIMIT = "timeMaxLimit";
    static int timeMaxLimit=null==System.getenv(TIME_MAX_LIMIT)?
            Integer.parseInt(System.getProperty(TIME_MAX_LIMIT,"10000")):
            Integer.parseInt(System.getenv(TIME_MAX_LIMIT));
    public static void main(String[] args) throws IOException {
        HttpServer httpServer = HttpServer.create(new InetSocketAddress(8989), 0);
        httpServer.createContext("/testVirtualThread", new HttpHandler() {
            @Override
            public void handle(HttpExchange exchange) throws IOException {
                String a="abcd";
                int b=1+1;
                System.out.println(a+b);
                CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(this::call, Executors.newVirtualThreadPerTaskExecutor());
                try {
                    String s = stringCompletableFuture.get();
                    System.out.println(s);
                } catch (InterruptedException | ExecutionException e) {
                    throw new RuntimeException(e);
                }
                OutputStream responseBody = exchange.getResponseBody();
                Headers responseHeaders = exchange.getResponseHeaders();
                responseHeaders.add("Content-Type","text/plain");
                exchange.sendResponseHeaders(200,2);
                responseBody.write("ok".getBytes(StandardCharsets.UTF_8));
                responseBody.flush();
                exchange.close();
            }

            public String call(){
                try {
                    Thread.sleep(Duration.ofMillis(current.nextInt(0,timeMaxLimit)));
                    return "ok";
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        httpServer.setExecutor(Executors.newThreadPerTaskExecutor(Thread.ofVirtual().name("vt-",1).factory()));
        httpServer.start();
    }
}
